package com.vshop.service.impl;

import com.vshop.config.datasource.DataSource;
import com.vshop.mapper.SequenceMapper;
import com.vshop.service.SequenceService;
import com.vshop.utils.sequence.DateUtils;
import com.vshop.utils.sequence.SequenceHepler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
/**
 * 序列生成实现类
 * @author lm
 * @date 2020/8/27 17:43
 */
public class SequenceServiceImpl implements SequenceService {
    @Resource
    private SequenceMapper sequenceMapper;

    private String PACKAGES_SEQ = "seq_getPackages_connseqno";

    private String TEMORDERID_SEQ = "seq_gettemporderid_connseqno";

    private String orderNoSeq = "seq_getOrderNo_connSeqNo";

    private String payIdSeq = "seq_getPayId_connSeqNo";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getPackageTaskNo() {
        String timeFix = DateUtils.format(new Date(), "yyyyMMdd");
        return SequenceHepler.generateSequence(
                /** 前缀 */
                String.format("%s%s", "P", timeFix),
                /** 当前序号值 */
                sequenceMapper.findCurrentVal(PACKAGES_SEQ),
                /** 数值长度 */
                10);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getTempOrderIdTaskNo() {

        String timeFix = DateUtils.format(new Date(), "yyyyMMdd");
        return SequenceHepler.generateSequence(
                /** 前缀 */
                String.format("%s%s", "T", timeFix),
                /** 当前序号值 */
                sequenceMapper.findCurrentVal(TEMORDERID_SEQ),
                /** 数值长度 */
                10);
    }

    /**
     * 激活卡片无支付过程但需要真的订购，因此要造假的单号
     * <p>
     * orderNo
     * <p>
     * 构成：N+yyyyMMddHHmmss+4位随机数
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getOrderNoTaskNo() {

        String timeFix = DateUtils.format(new Date(), "yyyyMMddHHmmss");
        return SequenceHepler.generateSequence(
                /** 前缀 */
                String.format("%s%s", "N", timeFix),
                /** 当前序号值 */
                sequenceMapper.findCurrentVal(orderNoSeq),
                /** 随机数数值长度 */
                4);
    }

    /**
     * 激活卡片无支付过程但需要真的订购，因此要造假的支付单号
     * <p>
     * payId
     * <p>
     * 构成：partnerCode+yyyyMMddHHmmss+4位随机数
     *
     * @param partnerCode
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getPayIdTaskNo(String partnerCode) {

        String timeFix = DateUtils.format(new Date(), "yyyyMMddHHmmss");
        return SequenceHepler.generateSequence(
                /** 前缀 */
                String.format("%s%s", partnerCode, timeFix),
                /** 当前序号值 */
                sequenceMapper.findCurrentVal(payIdSeq),
                /** 随机数数值长度 */
                4);
    }

}
